package com.uchengwang.ui.cm_ui.cycle.fm;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.basefm.BaseFragment;
import com.uchengwang.ui.cm_ui.cycle.adapter.FollowAdapter;
import com.uchengwang.ui.cm_ui.cycle.bean.CommentConfig;
import com.uchengwang.ui.cm_ui.cycle.bean.CommentItem;
import com.uchengwang.ui.cm_ui.cycle.bean.CycleSubPeopleSharesBean;
import com.uchengwang.ui.cm_ui.cycle.bean.H5ReportBean;
import com.uchengwang.ui.cm_ui.cycle.bridge.CircleContract;
import com.uchengwang.ui.cm_ui.cycle.bridge.CirclePresenter;
import com.uchengwang.ui.cm_ui.cycle.http.CycleHttpUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by U城网 on 2018/6/19.
 * 关注圈
 */

public class FragmentFollow extends BaseFragment implements CircleContract.CycleShareView, View.OnClickListener{
    private View view;
    private LRecyclerView follow_rv;
    private FollowAdapter adapter;
    private int page =1, totalPapers;
    private ActivityTitleBar titleBar;
    private long reFreshTime;//刷新时间
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private CirclePresenter presenter;

    private RelativeLayout load_bottom;
    private EditText bottom_edit;
    private Button bottom_bt;

    private CommentConfig mCommentConfig;
    private boolean isAllow = true;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setLayoutId(R.layout.fm_layout_follow);
        view = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);

        presenter = new CirclePresenter(this, getActivity());//回复评论 删除等的调取接口

        initView();

        return view;
    }

    private void initView(){
//        titleBar = view.findViewById(R.id.follow_titleBar);
        follow_rv = view.findViewById(R.id.follow_rv);

        load_bottom =  view.findViewById(R.id.load_bottom);
        load_bottom.setOnClickListener(this);
        bottom_edit =  view.findViewById(R.id.bottom_edit);
        bottom_bt =  view.findViewById(R.id.bottom_bt);
        bottom_bt.setOnClickListener(this);

        initData();
    }

    private void initData(){
//        titleBar.setTitle("关注", R.color.white);
//        titleBar.getTitleBar_bg().setBackground(null);
//
//        titleBar.setImageRight(R.drawable.fast_release_photo,  new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                final List<ChooseItemBean> chooseItemBeans = new ArrayList<>();
//                chooseItemBeans.add(new ChooseItemBean("享说", R.drawable.icon_main_speek, 0, R.color.ustudy_no_choose));
//                chooseItemBeans.add(new ChooseItemBean("视频", R.drawable.icon_main_video, 0, R.color.ustudy_no_choose));
//                chooseItemBeans.add(new ChooseItemBean("文章", R.drawable.icon_main_vote, 0, R.color.ustudy_no_choose));
//
//
//                PopupUtils.getUtils().rgihtMoreWithIcon(FragmentFollow.this.getContext(), titleBar, chooseItemBeans, R.drawable.shape_item_bg, new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                        PopupUtils.getUtils().dismiss();
//                        Intent intent = null;
//                        switch (chooseItemBeans.get(i).getTitle()){
//                            case "享说":
//                                intent = new Intent(FragmentFollow.this.getContext(), ReleaseDynamicActivity.class);
//                                break;
//                            case "视频":
//                                intent = new Intent(FragmentFollow.this.getContext(), ChooseVideoActivity.class);
//                                break;
//                            case "文章":
//                                intent = new Intent(FragmentFollow.this.getContext(), LoadCycleWebHtmlActivity.class);
//                                intent.putExtra(BaseConfig.IS_FULL, false);
//                                intent.putExtra(BaseConfig.IS_HIDE_RIGHT, true);
//                                intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/article/prepare");
//                                break;
//                        }
//                        if (intent != null){
//                            startActivity(intent);
//                        }
//                    }
//                });
//            }
//        });
//
//
//
//        titleBar.setImageLeft(R.drawable.club_release_msg_no, 96, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(FragmentFollow.this.getContext(), MsgNoticyActivity.class));
//                titleBar.setLeftMsg(View.GONE, 0);
//            }
//        });

        follow_rv.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new FollowAdapter(getContext());
        adapter.setBottomView(follow_rv);

        mLRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        follow_rv.setAdapter(mLRecyclerViewAdapter);

        adapter.setCirclePresenter(presenter);


        //设置头部加载颜色
        follow_rv.setHeaderViewColor(R.color.comment_color, R.color.uni_title_bar ,R.color.white);
        //设置底部加载颜色
        follow_rv.setFooterViewColor(R.color.comment_color, R.color.uni_title_bar ,R.color.white);
        //设置底部加载文字提示
        follow_rv.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        follow_rv.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData(true);
            }
        });

        follow_rv.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                if (page <= totalPapers){
                    //当前请求页大于总页数，不再请求
                    getData(false);
                } else {
                    follow_rv.setNoMore(true);
                }
            }
        });

        follow_rv.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        follow_rv.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        follow_rv.forceToRefresh();

    }

    @Override
    public void onResume() {
        super.onResume();

        if ((System.currentTimeMillis()- reFreshTime)/1000/60 >5){
            getRefresh();
        }

    }

    //获取更新信息
    private void getRefresh(){
        reFreshTime = System.currentTimeMillis();
//        CycleHttpUtils.getUtils().getCycleNotice(getActivity(), 1, 1, true, false, new OnHttpResultListener<CycleNoticeBean>() {
//            @Override
//            public void onResult(int status, String msg, int total, List<CycleNoticeBean> list) {
//                if (list != null){
//                    titleBar.setLeftMsg(View.VISIBLE, 0);
//                }
//            }
//        });

    }

    /**
     * 刷新数据
     * */
    public void onEvent(H5ReportBean h5ReportBean) {
        if (h5ReportBean != null){
            List<CycleSubPeopleSharesBean> data = adapter.getDatas();
            for (CycleSubPeopleSharesBean sharesBean : data){
                if (sharesBean.getShareType() == h5ReportBean.getReferType()){
                    switch (h5ReportBean.getReferType()){
                        case BaseConfig.SHARE_XIANG_SHUO:
                        case BaseConfig.SHARE_VIDEO:
                            if (sharesBean.getId() == h5ReportBean.getReferId()){
                                data.remove(sharesBean);
                                adapter.notifyDataSetChanged();
                                return;
                            }
                            break;

                        case BaseConfig.SHARE_ARTICLE:
                            if (sharesBean.getArticle().getId() == h5ReportBean.getReferId()){
                                data.remove(sharesBean);
                                adapter.notifyDataSetChanged();
                                return;
                            }
                            break;

                    }

                }
            }

        }
    }



    //获取网络数据
    private void getData(final boolean isRefresh){
        CycleHttpUtils.getUtils().getSubPeopleShares(getActivity(), page, 10, true, new OnHttpResultListener<CycleSubPeopleSharesBean>() {
            @Override
            public void onResult(int status, String msg, int total, List<CycleSubPeopleSharesBean> list) {

                if (isRefresh){
                    follow_rv.refreshComplete(10);
                    mLRecyclerViewAdapter.notifyDataSetChanged();
                }else {
                    follow_rv.refreshComplete(10);// REQUEST_COUNT为每页加载数量
                }

                if (list != null){
                    totalPapers = total;
                    if (isRefresh){
                        adapter.setDatas(list);
                    }else {
                        adapter.getDatas().addAll(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    //增加评论或者回复
    @Override
    public void addCmtOrReply(CommentConfig config, CommentItem addItem) {
        isAllow = true;
        if (addItem != null){
            bottom_edit.setText("");
            load_bottom.setVisibility(View.GONE);
            UCommonUtil.getUtil().hideSoftInput(getContext(), bottom_edit);

            CycleSubPeopleSharesBean sharesBean = adapter.getDatas().get(config.circlePosition);
            List<CommentItem> commentItems = sharesBean.getCommentItemLists();
            if (commentItems ==null){
                commentItems = new ArrayList<>();
            }
            commentItems.add(addItem);
            sharesBean.setCommentItemLists(commentItems);
            adapter.notifyDataSetChanged();

        }

    }

    //删除评论或者回复
    @Override
    public void deleteCmtOrReply(int circlePosition, long commentId) {
        if (circlePosition >-1 && commentId >-1){
            //说明删除成功
            CycleSubPeopleSharesBean sharesBean = adapter.getDatas().get(circlePosition);
            List<CommentItem> commentItems = sharesBean.getCommentItemLists();
            if (commentItems != null && commentItems.size() >0){
                for (CommentItem item : commentItems){
                    if (item.getId() == commentId){
                        commentItems.remove(item);
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            }


        }else {
            UCommonUtil.getUtil().showToast(getContext(), "删除失败");
        }
    }

    //打开输入框
    @Override
    public void editTextBodyVisible(int visibility, CommentConfig commentConfig) {
        mCommentConfig = commentConfig;
        bottom_edit.setVisibility(visibility);

        load_bottom.setVisibility(visibility);

        if (View.VISIBLE == visibility) {
            bottom_edit.requestFocus();
            if (bottom_edit.getText().toString().isEmpty() || "".equals(bottom_edit.getText().toString())) {
                if (CirclePresenter.ADD_CMT == commentConfig.commentType) {
                    bottom_edit.setHint("说点什么...");
                } else {
                    bottom_edit.setHint("回复 " + (commentConfig.replyUser == null ? "" : (commentConfig.replyUser.getName() + " : ")));
                }
            }
            //弹出键盘
            UCommonUtil.getUtil().showSoftInput(getContext(), bottom_edit);

        } else if (View.GONE == visibility) {
            //隐藏键盘
            UCommonUtil.getUtil().hideSoftInput(getContext(), bottom_edit);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.load_bottom:
                load_bottom.setVisibility(View.GONE);
                UCommonUtil.getUtil().hideSoftInput(getContext(), bottom_edit);
                break;

            case R.id.bottom_bt:
                if (presenter != null) {
                    //发布评论
                    String content = bottom_edit.getText().toString().trim();
                    if (TextUtils.isEmpty(content)) {
                        UCommonUtil.getUtil().showToast(FragmentFollow.this.getContext(), "评论内容不能为空...");
                        return;
                    }

                    if (!isAllow){
                        return;
                    }
                    isAllow = false;

                    MapRequest map = new MapRequest();
                    if (mCommentConfig.commentType == CirclePresenter.ADD_CMT) {
                        //对整个消息进行评论
                        map.put(BaseConfig.SHARE_ID, mCommentConfig.shareId);
                        map.put(BaseConfig.UID, UCommonUtil.getUtil().getId());
                        map.put(BaseConfig.NICK_NAME, UChengApplication.nickName);
                        map.put(BaseConfig.USER_AVATAR, UChengApplication.userAvatar);
                        map.put(BaseConfig.COMMEMT, content);

                    } else if (mCommentConfig.commentType == CirclePresenter.ADD_REPLY) {
                        map.put(BaseConfig.REPLY_CONTENT, content);
                        map.put(BaseConfig.CMT_ID, mCommentConfig.cmtId);

                        if (mCommentConfig.replyId >0){
                            //说明是对回复进行回复
                            map.put(BaseConfig.REPLY_ID, mCommentConfig.replyId);

                            if (mCommentConfig.replyUser != null){
                                map.put(BaseConfig.REPLY_UID, mCommentConfig.replyUser.getuId());
                                map.put(BaseConfig.REPLY_NICK_NAME, mCommentConfig.replyUser.getName());
                                map.put(BaseConfig.REPLY_USER_AVATAR, mCommentConfig.replyUser.getHeadUrl());
                            }
                        }
                    }
                    mCommentConfig.content = content;

                    presenter.addCycleCmtOrReply(mCommentConfig.commentType, map, mCommentConfig);
                }
                break;
        }
    }
}
